import BaseItemView from "../../../cfw/mvc/BaseItemView";
import GlobalEvent from "../../../cfw/event/GlobalEvent";
import { EventName } from "../../../public/Config";
import CristmasTreeManager from "../model/CristmasTreeManager";
import ModuleManager, { ModuleID } from "../../../cfw/module/ModuleManager";
import { ResType } from "../../../cfw/res/ResInterface";
import ResItem from "../../../cfw/res/ResItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CristmasTree extends BaseItemView {

    @property(cc.Sprite)
    light: cc.Sprite = null;


    @property([cc.Sprite])
    decorations: cc.Sprite[] = [];

    protected model:CristmasTreeManager;
    start() {
        this.model = CristmasTreeManager.instance();
        for (let index = 0; index < this.decorations.length; index++) {
            let id =this.model.getToyTypeData(index)
            this.updateToy(index,id)
        }
        this.updateLight(this.model.getLightID())
        GlobalEvent.instance().on(EventName.SELECT_LIGHT, this.updateLight, this)
        GlobalEvent.instance().on(EventName.SELECT_TOY, this.updateToy, this)
    }

    onDestroy() {
        GlobalEvent.instance().off(EventName.SELECT_LIGHT, this.updateLight, this)
        GlobalEvent.instance().off(EventName.SELECT_TOY, this.updateToy, this)
    }


    updateLight(id: number) {
        if (id > 0) {
            let light = CristmasTreeManager.instance().getLight(id)
            ModuleManager.getLoader(ModuleID.DECORATION).loadRes(light.getSprite(), ResType.SpriteFrame, (err, res: ResItem) => {
                if (err || !cc.isValid(this.node)) {
                    return;
                }
                this.light.spriteFrame = res.getRes()
            })

        } else {
            this.light.spriteFrame = null;
        }

    }


    updateToy(index: number, id: number) {

        if (id > 0) {
            let toy = CristmasTreeManager.instance().getToy(id)
            ModuleManager.getLoader(ModuleID.DECORATION).loadRes(toy.getIcon(), ResType.SpriteFrame, (err, res: ResItem) => {
                if (err || !cc.isValid(this.node)) {
                    return;
                }
                this.decorations[index].spriteFrame = res.getRes()
            })
        } else {
            this.decorations[index].spriteFrame = null;
        }

    }


}
